<?php
/**
 * Fastapp.
 * 4/25/24
 * @Author deepsea
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Wechat;

use App\Fastapp\Api\Service\BaseService;
use EasyWeChat\MiniApp\Application;
use League\Flysystem\Filesystem;

class MiniService extends BaseService
{
    public function qrcode(array $data): string
    {
        $dir = '/qrcode/' . date('Ymd');
        $path = $dir . '/' . $data['filename'];
        /** @var Filesystem $filesystem */
        [$filesystem] = get_filesystem();

        try {
            if ($filesystem->fileExists($path)) return fgets($filesystem->readStream($path));
        } catch (\Throwable) {
        }

        $response = $this->app()->getClient()->post('/wxa/getwxacodeunlimit', [
            'json' => [
                'page' => $data['path'],
                'scene' => $data['scene'],
                'check_path' => !(config('app_env') == 'dev'),
                'env_version' => config('app_env') == 'dev' ? 'develop' : 'release',
            ]
        ]);
        base642image($response->getContent(), $dir, $data['filename'], is_binary: true);
        return $response->getContent();
    }

    public function app(): Application
    {
        $config = api_cache()->getConfigByGroupKey('wechat');
        $config = [
            'app_id' => $config['mini_app_id'],
            'secret' => $config['mini_secret'],
            'aes_key' => $config['mini_aes_key'],
            'token' => $config['mini_token'],
            'http' => [
                'throw' => true,
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
                'retry' => true,
            ],
        ];
        $app = new Application($config);
        $app->setCache(container()->get(\Psr\SimpleCache\CacheInterface::class));
        return $app;
    }
}